package com.bea.ftd.dashboard.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bea.ftd.common.ValidationException;
import com.bea.ftd.common.dao.SignInfoRepo;
import com.bea.ftd.common.entity.SignInfo;
import com.bea.ftd.common.enums.ValidationErrorCode;
import com.bea.ftd.dashboard.service.IGatewayService;
import com.bea.ftd.dashboard.service.ISignInfoService;
import com.bea.ftd.dashboard.validator.BooleanValidator;
import com.bea.ftd.dashboard.validator.CustomTypeValidator;
import com.bea.ftd.dashboard.validator.NumberValidator;
import com.bea.ftd.dashboard.validator.StringValidator;

@Service
public class SignInfoServiceImpl implements ISignInfoService, IGatewayService {
	private Logger LOGGER = LoggerFactory.getLogger(SignInfoServiceImpl.class);

	@Autowired
	private SignInfoRepo signInfoRepo;
	@Autowired
	private StringValidator stringValidator;
	@Autowired
	private BooleanValidator booleanValidator;
	@Autowired
	private NumberValidator numberValidator;
	@Autowired
	private CustomTypeValidator customTypeValidator;

	@Override
	public void addSignInfo(SignInfo signInfo) throws ValidationException {

		validateInputParams(signInfo);
		setCreateOrUpdateTime(signInfo, signInfoRepo);
		signInfoRepo.save(signInfo);
	}

	/**
	 * 验证输入参数是否有效
	 * 
	 * @param signInfo
	 * @throws ValidationException
	 */
	private void validateInputParams(SignInfo signInfo) throws ValidationException {
		if (stringValidator.isEmptyString(signInfo.getPartnerCode())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "合作商户号不能为空");
		}

		if (!numberValidator.isNonNegtiveNumber(signInfo.getSignId())) {
			throw new ValidationException(ValidationErrorCode.INVALID_NUMBER, "无效的签名ID");
		}

		if (stringValidator.isEmptyString(signInfo.getPrivateKeyPath())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "私钥路径不能为空");
		}

		if (stringValidator.isEmptyString(signInfo.getPublicKeyPath())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "公钥路径不能为空");
		}

		if (!booleanValidator.isBooleanType(signInfo.getIsActivated())) {
			throw new ValidationException(ValidationErrorCode.INVALID_BOOLEAN_VALUE, "无效的isActivated值");
		}

	}

	@Override
	public List<SignInfo> getAllSignInfos() {
		try {
			return signInfoRepo.findAll();
		} catch (Exception e) {
			LOGGER.error("error when querying signInfo from database " + e.getMessage());
			return null;
		}
	}
}
